package ldh.im.dto.codec.json;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import ldh.im.ImCoder;
import ldh.im.dto.base.Dto;
import ldh.im.util.JsonUtil;

import java.lang.reflect.Type;
import java.nio.charset.Charset;

public class JsonCoder<T extends Dto> implements ImCoder<T, ByteBuf> {

    private Class<T> clazzT;
    private Type type;

    public JsonCoder(Class<T> clazzT) {
        this.clazzT = clazzT;
    }

    public JsonCoder(Type type) {
        this.type = type;
    }

    public T decode(ByteBuf data) {
        String strData = data.toString(Charset.forName("utf8"));
        data.skipBytes(data.readableBytes());
        if (clazzT != null) {
            return JsonUtil.toObject(strData, clazzT);
        }
        return JsonUtil.toObject(strData, type);
    }

    @Override
    public ByteBuf encode(T to) {
        String json = JsonUtil.toJson(to);
        return Unpooled.copiedBuffer(json, CharsetUtil.UTF_8);
    }
}
